import React, { useState, useEffect } from 'react';
import { registerMicroApps, start, setDefaultMountApp } from 'qiankun';
import './index.css';

const App = () => {
  const [activeApp, setActiveApp] = useState('home');
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    // 注册微应用（vanilla-app 不通过 qiankun 加载，使用 iframe 方式）
    registerMicroApps([
      {
        name: 'vue2-app',
        entry: '//localhost:3001',
        container: '#microapp-container',
        activeRule: '/vue2',
        props: {
          routerBase: '/vue2'
        }
      },
      {
        name: 'vue3-app', 
        entry: '//localhost:3002',
        container: '#microapp-container',
        activeRule: '/vue3',
        props: {
          routerBase: '/vue3'
        }
      },
      {
        name: 'react-app',
        entry: '//localhost:3003', 
        container: '#microapp-container',
        activeRule: '/react',
        props: {
          routerBase: '/react'
        }
      }
    ], {
      beforeLoad: (app) => {
        console.log('before load', app);
        setLoading(true);
        return Promise.resolve();
      },
      beforeMount: (app) => {
        console.log('before mount', app);
        return Promise.resolve();
      },
      afterMount: (app) => {
        console.log('after mount', app);
        setLoading(false);
        return Promise.resolve();
      },
      beforeUnmount: (app) => {
        console.log('before unmount', app);
        return Promise.resolve();
      },
      afterUnmount: (app) => {
        console.log('after unmount', app);
        return Promise.resolve();
      }
    });

    // 启动 qiankun
    start({
      prefetch: false, // 禁用预加载
      sandbox: {
        strictStyleIsolation: false, // 关闭严格样式隔离
        experimentalStyleIsolation: true // 使用实验性样式隔离
      }
    });
  }, []);

  // 渲染原生应用的 iframe
  const renderVanillaApp = () => {
    const container = document.getElementById('microapp-container');
    if (!container) {
      console.error('❌ 找不到微应用容器');
      return;
    }

    // 清空容器
    container.innerHTML = '';
    
    // 创建加载提示
    const loadingDiv = document.createElement('div');
    loadingDiv.innerHTML = `
      <div style="
        padding: 10px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 8px;
        margin-bottom: 10px;
      ">
        <h3 style="color: white; text-align: center; margin: 0;">
          🟨 原生 JavaScript 应用 (iframe 模式)
        </h3>
        <p style="color: rgba(255,255,255,0.8); text-align: center; margin: 5px 0 0 0; font-size: 14px;">
          完全隔离的原生网页，新手可直接编辑 vanilla-app/public/native.html
        </p>
      </div>
      <div style="
        width: 100%;
        height: 80vh;
        display: flex;
        align-items: center;
        justify-content: center;
        background: white;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
      ">
        <div style="text-align: center; color: #666;">
          <div style="font-size: 24px; margin-bottom: 10px;">⏳</div>
          <div>正在加载原生应用...</div>
        </div>
      </div>
    `;
    
    container.appendChild(loadingDiv);

    // 延迟创建iframe，确保容器渲染完成
    setTimeout(() => {
      const iframe = document.createElement('iframe');
      // 使用相对路径，如果是同域的话
      iframe.src = 'http://localhost:3004/native.html?t=' + Date.now();
      iframe.style.cssText = `
        width: 100%;
        height: 80vh;
        border: none;
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
        background: white;
      `;
      
      iframe.onload = () => {
        console.log('🟨 原生应用 iframe 加载完成！');
        setLoading(false);
      };
      
      iframe.onerror = () => {
        console.error('❌ 原生应用 iframe 加载失败！');
        container.innerHTML = `
          <div style="
            padding: 20px;
            text-align: center;
            color: #ff6b6b;
            background: white;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
          ">
            <h3>❌ 原生应用加载失败</h3>
            <p>请确保原生应用服务器正在运行 (http://localhost:3004)</p>
            <button onclick="location.reload()" style="
              padding: 10px 20px;
              background: #007bff;
              color: white;
              border: none;
              border-radius: 5px;
              cursor: pointer;
              margin-top: 10px;
            ">重新加载</button>
          </div>
        `;
        setLoading(false);
      };

      // 替换加载提示为实际的iframe
      const iframeContainer = container.querySelector('div:last-child');
      if (iframeContainer) {
        iframeContainer.replaceWith(iframe);
      }
    }, 200);
  };

  // 监听activeApp变化，确保原生应用正确渲染
  useEffect(() => {
    if (activeApp === 'vanilla') {
      // 延迟一点时间确保DOM已更新
      const timer = setTimeout(() => {
        const container = document.getElementById('microapp-container');
        if (container && container.style.display !== 'none') {
          renderVanillaApp();
        }
      }, 100);
      return () => clearTimeout(timer);
    }
  }, [activeApp]);

  const handleAppSwitch = (appName) => {
    setActiveApp(appName);

    if (appName === 'home') {
      // 显示首页内容
      window.history.pushState({}, '', '/');
    } else if (appName === 'vanilla') {
      // 原生应用使用 iframe 方式，不走 qiankun
      window.history.pushState({}, '', '/vanilla');
      // renderVanillaApp 由 useEffect 处理
    } else {
      // 其他应用确保容器存在后再进行路由跳转
      setTimeout(() => {
        if (appName === 'vue2') {
          window.history.pushState({}, '', '/vue2');
        } else if (appName === 'vue3') {
          window.history.pushState({}, '', '/vue3');  
        } else if (appName === 'react') {
          window.history.pushState({}, '', '/react');
        }
        
        // 触发路由变化
        window.dispatchEvent(new PopStateEvent('popstate'));
      }, 100);
    }
  };

  const renderHome = () => (
    <div className="home-content">
      <h2>🎉 qiankun 微前端教学项目</h2>
      <p>每个技术栈都包含两个页面：<strong>Todo List</strong> 和 <strong>空白页面</strong></p>
      
      <div className="features">
        <div className="feature-card">
          <h3>📝 Todo List 页面</h3>
          <ul>
            <li>✅ 基础的增删改查功能</li>
            <li>✅ 展示各框架的核心特性</li>
            <li>✅ 简洁易懂的代码结构</li>
            <li>✅ 适合学习和对比</li>
          </ul>
        </div>
        
        <div className="feature-card">
          <h3>🎨 空白页面</h3>
          <ul>
            <li>✅ 干净的起始页面</li>
            <li>✅ 方便自己编写代码</li>
            <li>✅ 练习各框架语法</li>
            <li>✅ 对照学习不同技术栈</li>
          </ul>
        </div>
      </div>

      <div className="framework-info">
        <div className="framework-card vue2">
          <h3>💚 Vue 2</h3>
          <p>选项式 API</p>
          <p>成熟稳定的框架</p>
          <button onClick={() => handleAppSwitch('vue2')} className="btn btn-primary">
            进入应用
          </button>
        </div>
        <div className="framework-card vue3">
          <h3>💎 Vue 3</h3>
          <p>组合式 API</p>
          <p>现代化的响应式</p>
          <button onClick={() => handleAppSwitch('vue3')} className="btn btn-primary">
            进入应用
          </button>
        </div>
        <div className="framework-card react">
          <h3>⚛️ React</h3>
          <p>Hooks 模式</p>
          <p>函数式组件</p>
          <button onClick={() => handleAppSwitch('react')} className="btn btn-primary">
            进入应用
          </button>
        </div>
        <div className="framework-card vanilla">
          <h3>🟨 原生 JS</h3>
          <p>纯 JavaScript</p>
          <p>最基础的实现</p>
          <button onClick={() => handleAppSwitch('vanilla')} className="btn btn-primary">
            进入应用
          </button>
        </div>
      </div>

      <div style={{marginTop: '30px', padding: '20px', background: '#f8f9fa', borderRadius: '8px'}}>
        <h4>💡 使用说明</h4>
        <ul style={{textAlign: 'left', color: '#666'}}>
          <li>每个应用内部都有导航，可以切换 Todo List 和空白页面</li>
          <li>Todo List 展示了各框架的基本用法和语法差异</li>
          <li>空白页面提供了干净的环境，方便你自己编写代码练习</li>
          <li>可以同时打开多个应用，对比不同框架的实现方式</li>
        </ul>
      </div>
    </div>
  );

  return (
    <div className="app">
      <div className="container">
        <header className="header">
          <h1>🚀 qiankun 微前端项目</h1>
          <p>Vue2 + Vue3 + React 18+ + 原生JS 完美集成</p>
        </header>

        <nav className="navigation">
          <button 
            className={`nav-button ${activeApp === 'home' ? 'active' : ''}`}
            onClick={() => handleAppSwitch('home')}
          >
            🏠 首页
          </button>
          <button 
            className={`nav-button ${activeApp === 'vue2' ? 'active' : ''}`}
            onClick={() => handleAppSwitch('vue2')}
          >
            💚 Vue 2
          </button>
          <button 
            className={`nav-button ${activeApp === 'vue3' ? 'active' : ''}`}
            onClick={() => handleAppSwitch('vue3')}
          >
            💎 Vue 3
          </button>
          <button 
            className={`nav-button ${activeApp === 'react' ? 'active' : ''}`}
            onClick={() => handleAppSwitch('react')}
          >
            ⚛️ React
          </button>
          <button 
            className={`nav-button ${activeApp === 'vanilla' ? 'active' : ''}`}
            onClick={() => handleAppSwitch('vanilla')}
          >
            🟨 原生 JS
          </button>
        </nav>

        <main className="content-area">
          {loading && (
            <div className="loading">
              <div className="loading-spinner"></div>
              <p>正在加载应用...</p>
            </div>
          )}
          
          {activeApp === 'home' && (
            renderHome()
          )}
          
          <div 
            id="microapp-container" 
            className="microapp-container"
            style={{ display: activeApp === 'home' ? 'none' : 'block' }}
          >
            {/* 微应用将在这里渲染 */}
          </div>
        </main>
      </div>
    </div>
  );
};

export default App;